package com.example.myapplication;


import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

// DBHelper.java
public class DBMysqlHelper {
    private static final String URL = "jdbc:mysql://192.168.8.111:3306/health_monitor?useSSL=false&allowPublicKeyRetrieval=true";

    private static final String USER = "root";
    private static final String PASSWORD = "root";

    public Connection connect() throws ClassNotFoundException,  java.sql.SQLException {
        Class.forName("com.mysql.jdbc.Driver");
        return DriverManager.getConnection(URL, USER, PASSWORD);
    }


    /**
     * 注册新用户
     *
     * @param username 用户名
     * @param password 密码（明文）
     * @return 注册是否成功
     */
    public boolean registerUser(String username, String password) {


        String query = "INSERT INTO tb_user (username, password) VALUES (?, ?)";

        try (Connection conn = connect();
             PreparedStatement stmt = conn.prepareStatement(query)) {

            stmt.setString(1, username);
            stmt.setString(2, password);
            stmt.executeUpdate();
            return true;

        } catch (SQLException | ClassNotFoundException e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 用户登录验证
     *
     * @param username 用户名
     * @param password 密码（明文）
     * @return 如果用户名和密码匹配，返回用户ID；否则返回 -1
     */
    public int loginUser(String username, String password) {


        String query = "SELECT id FROM tb_user WHERE username = ? AND password = ?";

        try (Connection conn = connect();
             PreparedStatement stmt = conn.prepareStatement(query)) {

            stmt.setString(1, username);
            stmt.setString(2, password);
            ResultSet rs = stmt.executeQuery();

            if (rs.next()) {
                return rs.getInt("id");
            } else {
                return -1; // 登录失败
            }

        } catch (SQLException | ClassNotFoundException e) {
            e.printStackTrace();
            return -1;
        }
    }

}
